package XML与JSON.使用DOM;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class Test { 
	public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {
		File file = new File("src\\main\\java\\XML与JSON\\使用DOM\\student1.xml");
		Document doc=getDocumentInstance(file);
		Element root = (Element) doc.getDocumentElement();
		visit(root);
	}
	
		//对获取document对象进行封装
	public static Document getDocumentInstance(File xmlfile) throws SAXException, IOException, ParserConfigurationException {
		DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc =builder.parse(xmlfile);
		return doc;
	}
//对文档进行遍历的通用方法
	public static void visit(Node start) {
		if(start.getNodeName()!="#text")
		System.out.println(start.getNodeName()+"……"+start.getNodeValue());
        // 确保传递的节点对象是Element 
		//  因为Attribute 一定在Element中
 
		if(start.getNodeType()==Node.ELEMENT_NODE) {
			NamedNodeMap nnm=start.getAttributes();
        // 处理属性节点对象
			for(int i=0;i<nnm.getLength();i++) {
				Node arr = nnm.item(i);
				if(start.getNodeName()!="#text")
				System.out.println(arr.getNodeName()+"……"+arr.getNodeValue());
			}
			for(Node sub=start.getFirstChild();sub!=null;sub=sub.getNextSibling()) {
				visit(sub);//采用递归的方式实现
			}
		}
	}
    //对输出功能的封装
	public static void print(Document dc,String name) {
		NodeList list = dc.getElementsByTagName(name);
		for(int i=0;i<list.getLength();i++) {
			Element e = (Element) list.item(i);
			System.out.print("id:"+e.getAttribute("id"));
			System.out.print(list.item(i).getTextContent());
		}	
 
	}
}